package repository

import (
	"github.com/lab-online/internal/course/entity"
	"github.com/lab-online/internal/course/infra/model"
)

// SaveCourse 若未指定 ID 则新增，否则更新非零字段
func (r *Repository) SaveCourse(courseEntity entity.CourseEntity) (entity.CourseEntity, error) {
	course := model.NewCourse(model.WithCourseEntity(courseEntity))

	var err error
	if course.ID == 0 {
		err = r.createCourse(course)
	} else {
		err = r.updateCourse(course)
	}

	if err != nil {
		return nil, errorHandler(err)
	} else {
		return course.ToEntity(nil), nil
	}
}

func (r *Repository) createCourse(course *model.Course) error {
	return r.db.Create(course).Error
}

func (r *Repository) updateCourse(course *model.Course) error {
	return r.db.Model(course).Updates(course).Error
}

// SaveExperiment 若未指定 ID 则新增，否则更新非零字段
func (r *Repository) SaveExperiment(experimentEntity entity.ExperimentEntity) (entity.ExperimentEntity, error) {
	experiment := model.NewExperiment(model.WithExperimentEntity(experimentEntity))

	var err error
	if experiment.ID == 0 {
		err = r.db.Create(experiment).Error
	} else {
		err = r.db.Model(experiment).Updates(experiment).Error
	}

	if err != nil {
		return nil, errorHandler(err)
	} else {
		return experiment.ToEntity(), nil
	}
}
